package com.jxs.android.ges;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.soap.SoapUtil;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.util.StringUtils;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.TopBar;

@SuppressLint("HandlerLeak")
public class WorkLogGetSmsContent extends AbstractActivity {
	// 2.4.6 getSmsContent 【获取发送页面内容】
	private BuLoadingDailog progressDialog;
	private String wl_id = "";
	private Context context;
	private PhoneAdapter adapter;
	private ArrayList<String> phones = new ArrayList<String>();

	private TextView senderInfo;// 工号
	private EditText send_conent;// 电话号码
	private TextView send_conent_count;// 姓名
	private TextView send_conent_count_all;
	private ListView phone_list;// 分公司
	private Button phone_slected;
	private ImageButton phone_input_sure;
	private EditText phone_input;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;
		initTopBar(savedInstanceState, R.layout.bu_work_log_get_sms_content);
		initUI();
		if (null != getIntent() && getIntent().hasExtra("wl_id")) {
			wl_id = getIntent().getStringExtra("wl_id");
		}
		phone_slected.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, WorkLogGetSystemContactList.class);
				startActivityForResult(intent, REQ_CODE);
			}
		});
		getSmsContent();
		adapter = new PhoneAdapter(phones);
		phone_list.setAdapter(adapter);
	}

	private void initUI() {
		senderInfo = (TextView) findViewById(R.id.senderInfo);// 工号
		send_conent = (EditText) findViewById(R.id.send_conent);// 工号
		send_conent_count = (TextView) findViewById(R.id.send_conent_count);// 姓名
		send_conent_count_all = (TextView) findViewById(R.id.send_conent_count_all);// 姓名

		InputFilter[] filters = { new LengthFilter(800) };
		send_conent.setFilters(filters);

		send_conent_count_all.setText("/" + 800);
		phone_list = (ListView) findViewById(R.id.phone_list);// 分公司
		phone_slected = (Button) findViewById(R.id.phone_slected);// 分公司
		phone_input = (EditText) findViewById(R.id.phone_input);// 分公司
		phone_input_sure = (ImageButton) findViewById(R.id.phone_input_sure);// 分公司

		send_conent.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				send_conent_count.setText(s.length() + "");
			}
		});
		phone_input_sure.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (StringUtils.isEmpety(phone_input.getText().toString())) {
					errorMsgPop("请输入号码后添加！");
					return;
				} else {
					phones.add(phone_input.getText().toString());
					adapter.notifyDataSetChanged();
					phone_input.setText("");
				}
			}
		});

	}

	private final int REQ_CODE = 0xa02;
	final int REQ_SENDER_LIST = 0xc001;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (REQ_CODE == requestCode && resultCode == RESULT_OK) {
			phones.addAll(data.getExtras().getStringArrayList("phones"));
			adapter.notifyDataSetChanged();
		}
		if (REQ_SENDER_LIST == requestCode && resultCode == RESULT_OK) {
			this.finish();
		}
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		super.topBarReturn(topBar);
		topBar.setLogicBtnText("预览");
		topBar.setTitle("发送短信");
		topBar.showLogicBtn();
		topBar.hindFilter();
		topBar.hindSpinnerBtn();
		topBar.setLogicBtnListern(new TopBar.LogicBtnListern() {
			@Override
			public void onClickLogicBtn() {
				if (phones.isEmpty() || phones.size() == 0) {
					errorMsgPop("未添加号码！");
					return;
				}
				Intent intent = new Intent(context, WorkLogGetSenderInfoList.class);
				Bundle bundle = new Bundle();
				bundle.putString("content", send_conent.getText().toString() + "");
				bundle.putStringArrayList("phones", phones);
				bundle.putString("senderInfo", senderInfo.getText().toString() + "");
				intent.putExtras(bundle);
				startActivityForResult(intent, REQ_SENDER_LIST);
			}
		});
	}

	private void getSmsContent() {
		progressDialog = new BuLoadingDailog(this);
		progressDialog.showLoading(R.string.load_and_wait);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getSmsContent(GesApplication.getUserInfo().getTicket(), wl_id);
			}
		}).start();
	}

	private void getSmsContent(String ticket, String wl_id) {
		// 2.4.3 getSmsContent 【获取工作日志详单接口】
		String wsdl_url = GesApplication.WSDL_URL;// wsdl
		String namespace = GesApplication.WSDL_NAME_SPACE;// namespace
		String methodName = "getSmsContent";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", ticket);
		request.addProperty("wl_id", wl_id);
		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paser(response);
			}

			@Override
			public void error(String message, Exception e) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			}

		});
	}

	private void paser(SoapObject soapObject) {
		if (null != soapObject) {
			String stauts = soapObject.getProperty("status").toString();
			SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
			String message = msgObjec.getProperty("message").toString();
			if ("-2".equals(stauts)) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("-1".equals(stauts)) {
				Message msg = new Message();
				msg.what = TO_LOGIN;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("0".equals(stauts)) {
				Message msg = new Message();
				msg.what = UPDATE_LIST_UI;
				msg.obj = (SoapObject) soapObject.getProperty("retMsg");
				handler.sendMessage(msg);
			}
		}
	}

	private final int UPDATE_LIST_UI = 0x101;
	private final int ERROR_MSG = 0x1013;
	private final int TO_LOGIN = 0x1019;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			if (!MemoryUtil.isCurrentActivity(WorkLogGetSmsContent.class)) {
				return;
			}

			if (null != progressDialog && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			if (msg.what == UPDATE_LIST_UI) {
				initContentData((SoapObject) msg.obj);
			} else if (msg.what == ERROR_MSG) {
				errorMsgPop(msg.obj.toString());
			} else if (msg.what == TO_LOGIN) {
				errorMsgToLogin(msg.obj.toString());
			}
		}
	};

	private void initContentData(SoapObject retMsgObject) {
		if (null != retMsgObject) {
			send_conent.setText(SoapUtil.getValue(retMsgObject, "content"));
			// <senderInfo>甘肃电信客户经理：系统管理员</senderInfo>
			senderInfo.setText(SoapUtil.getValue(retMsgObject, "senderInfo"));
			SoapObject phoneList = (SoapObject) retMsgObject.getProperty("phoneList");
			Log.e("TAG", phoneList.toString() + "--");
		}
	}

	private class PhoneAdapter extends BaseAdapter {

		class ViewHolder {
			TextView phone;// :所属行业
			ImageView delete;
		}

		private LayoutInflater inflater = null;
		private ViewHolder holder = null;

		public PhoneAdapter(List<String> contactInfos) {
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return phones.size();
		}

		public String getItem(int position) {
			return phones.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final String contact = phones.get(position);
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.bu_work_log_get_sms_content_item, null);
				holder = new ViewHolder();
				holder.phone = (TextView) convertView.findViewById(R.id.phone);
				holder.delete = (ImageView) convertView.findViewById(R.id.delete);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.phone.setText(contact);
			holder.delete.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					phones.remove(contact);
					notifyDataSetChanged();
				}
			});
			return convertView;
		}

	}
}
